package io.github.weiranyi;

import redis.clients.jedis.Jedis;

import java.io.IOException;

/**
 * 3 解决库存遗留问题【通过LUA脚本】
 */
public class SecKill3 {
    // 事务也交给脚本做了
    static String secKillScript ="local userid=KEYS[1];\r\n" +
            "local prodid=KEYS[2];\r\n" +
            "local qtkey='sk:'..prodid..\":kc\";\r\n" +
            "local usersKey='sk:'..prodid..\":usr\";\r\n" +
            "local userExists=redis.call(\"sismember\",usersKey,userid);\r\n" +
            "if tonumber(userExists)==1 then \r\n" +
            "   return 2;\r\n" +
            "end\r\n" +
            "local num= redis.call(\"get\" ,qtkey);\r\n" +
            "if tonumber(num)<=0 then \r\n" +
            "   return 0;\r\n" +
            "else \r\n" +
            "   redis.call(\"decr\",qtkey);\r\n" +
            "   redis.call(\"sadd\",usersKey,userid);\r\n" +
            "end\r\n" +
            "return 1" ;
    public static boolean doSecKill(String uid,String prodid) throws IOException {

        Jedis jedis = new Jedis("192.168.128.128",6379);
        // 加载LUA脚本
        String sha1=  jedis.scriptLoad(secKillScript);
        // 执行LUA脚本
        Object result= jedis.evalsha(sha1, 2, uid,prodid);
        // 得到执行脚本结果
        String reString=String.valueOf(result);
        if ("0".equals( reString )  ) {
            System.err.println("已抢空！！");
        }else if("1".equals( reString )  )  {
            System.out.println("抢购成功！！！！");
        }else if("2".equals( reString )  )  {
            System.err.println("该用户已抢过！！");
        }else{
            System.err.println("抢购异常！！");
        }
        jedis.close();
        return true;
    }
}
